package com.netty.encodedecode.protol;

import com.netty.encodedecode.memreport.DirectMemReporter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @auther: cc.ly
 * @date: 2019/1/12/012
 */

public class Server {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossLoop = new NioEventLoopGroup();
        EventLoopGroup workLoop = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(bossLoop, workLoop).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new PersonProtolDecode());
                        pipeline.addLast(new PersonProtolEncode());
                        pipeline.addLast(new ServerHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.bind(8887).sync();
        channelFuture.addListeners(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    new DirectMemReporter().startReport();
                }
            }
        });
        channelFuture.channel().closeFuture().sync();
    }
}
